<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

// ### AclAssistant : Community
class Action_Node_ShowHp extends RL_Handler
{
	var $ajax_functions = array(
		//'ajax_showConfig', // выводит конфиг сообщества (сами виджеты + расположение пока там)
		'ajax_updateLayout', // обновляет расположение виджетов
		'ajax_addWidget', // добавляет новый фиджет
		'ajax_renderWidget', // возвращает отрендеренный виджет
		'ajax_getSettingsHtml', // возвращает шаблон с настройками виджета
		'ajax_updateSettings', // обновляет настройки виджета
		'ajax_deleteWidget', // удаляет виджет
		//'ajax_execWidget'
	);
	var $template_data = array();
	var $widgets = array();
	
	private $moderator_mode = false;

	private function toTemplate(array $to_add) {
		$this->template_data = array_merge($to_add, $this->template_data);
	}

	public function init() {
		$this->rh->UseClass('RL_CyrDate');
		$this->acla = $this->module->aa;
		$this->acld = $this->acla->getInfo();
		$this->acla->getAvailableOperations();
		$this->store = &$this->ctx->store;

		if ( 'administrator' == $this->ctx->mm->aa->acl_data['role']['name'] ) {
			$this->moderator_mode = true;
		}
		
		$this->widgets = array(
			'login' => array(
				'name' => 'LoginWidget',
				'position' => 'column1',
			),
			'communities' => array(
				'name' => 'NodeCommunitiesWidget',
				'position' => 'column1',
			),
		);
	}

	private function getCommunities()
	{
		$items = array();
		$rs = $this->store->find("objects where objects.type = :0 and objects.is_deleted=0 order by objects.ctime desc limit 0,5", array("fcommunity"));
		while ($obj = $rs->next()) {
			$items[] = array_merge($obj->data, array(
				'ctime' => RL_CyrDate::newFromStr("%Y-%m-%d %H:%i:%s", $obj->ctime),
				'oid' => $obj->id
			));
		}

		return array("communities"=>$items);
	}

	// http://ot2.peopleid.ru/users/sixtyone/
	public function process ()
	{
		$this->toTemplate( $this->acla->template_data );
		//$this->toTemplate( $this->getCommunities() );

		// set view
		$view = $this->rh->views->findByName('hp');
		$view->data = $this->template_data;
		
		$this->fillWidgetsList();
		
		$view->data['__widgets__'] = $this->widgets;
		
		$view->data['reg_iframe_url'] = $this->rh->idsrv_regiframe_url;

		$view->data['trust_root'] = urlencode($this->rh->base_url);
		$view->data['e_fetcher_url'] = trim($this->rh->base_url, "/")."/eventsfetcher/";
		$view->data['return_url'] = urlencode($this->rh->base_url."login?openid_action=login&ref=".$this->rh->base_url);
		
		$view->data['is_hostpage'] = true;
		
		$this->rh->response->setContent( $view );
	} // end of function execute

	public function ajax_addWidget( $column, $type ) {
		$this->ctx->db->begin();
		$column = substr($column, 6, 1);
		
		// итак находим объект сообщества, затем переопределяем массив config и сохраняем
		$widget = array(
			"params"=>array(), // параметры виджета
			"name"=>$type,
		);
		
		$node = $this->store->getObject(1);
		if ( !isset($node->data['widgets']) ) {
			$node->data['widgets'] = array();
		}
		$node->data['widgets'][] = $widget;
		end($node->data['widgets']);

		$new_widget_id = key($node->data['widgets']);
		
		if ( isset($node->data['widgets_layout'][$column]) ) {
			array_unshift( $node->data['widgets_layout'][$column], $new_widget_id );
		} else {
			$node->data['widgets_layout'][$column][] = $new_widget_id;
		}
		
		$node->save();
		
		$this->ctx->db->end();
		
		$this->ctx->cp->set_data( $new_widget_id );
	}
	
	public function ajax_renderWidget ( $widget_id ) {
		$cp = &$this->ctx->cp;
		$nd_html = &$cp->add_node('html');
		$this->fillWidgetsList();

		$widget = $this->widgets[ $widget_id ];
		if ( !empty($widget) ) {
			$view = $widget->getView();
			$view->data['widget'] = $widget->render();
			
			$html = $view->getContent();
			$nd_html->set_data( $html );
			
			$nd_id = &$cp->add_node('widget_id');
			$nd_id->set_data( $widget_id );
		}
	}
	
	private function fillWidgetsList() {
		$node = $this->store->getObject(1);
		
		if ( isset($node->data['widgets']) ) {
			foreach ( $node->data['widgets'] as $id=>$widget ) {
				foreach ( $this->widgets as $key=>$val ) {
					if ( $val['name'] == $widget['name'] ) {
						unset($this->widgets[$key]);
						break;
					}
				}
				//$this->widgets[$id+0] = $widget;
			}
		}
		
		$widgets = array();
		
		if ( !empty($this->widgets) ) {
			foreach ( $this->widgets as $widget_id=>$widget ) {
				$object = widgets_create($this->widgets[$widget_id]['name']);
				if ( !($object instanceof StdClass) ) {
					$widgets[$widget_id] = $object;
					if ( !empty($node->data['widgets'][$widget_id]['params']) ) {
						$widgets[$widget_id]->setParams($node->data['widgets'][$widget_id]['params']);
					}
					$widgets[$widget_id]->widget_id = $widget_id;
					$widgets[$widget_id]->widget_position = $this->widgets[$widget_id]['position'];
					$widgets[$widget_id]->ctx = $this->ctx;
					$widgets[$widget_id]->acl_assistant = $this->acl_assistant;
					$widgets[$widget_id]->moderator_mode = $this->moderator_mode;
				}
			}
		}
		
		$pageWidgets = array();
		
		if ( $node->data['widgets_layout'] ) {
			foreach ($node->data['widgets_layout'] as $position=>$layout) {
				foreach ($layout as $level=>$widget_id) {
					if ( isset($widgets[$widget_id]) && !empty($widgets[$widget_id]) ) {
						$pageWidgets[$widget_id] = $widgets[$widget_id];
						if ( !empty($this->widgets[$widget_id]['params']) ) {
							$pageWidgets[$widget_id]->setParams($this->widgets[$widget_id]['params']);
						}
						$pageWidgets[$widget_id]->widget_position = 'column' . $position;
						unset($widgets[$widget_id]);
					} else {
						$widget = widgets_create($node->data['widgets'][$widget_id]['name']);
						
						if ( empty($widget) ) {
							continue;
						}
						
						$pageWidgets[$widget_id] = $widget;
						if ( !empty($node->data['widgets'][$widget_id]['params']) ) {
							$pageWidgets[$widget_id]->setParams($node->data['widgets'][$widget_id]['params']);
						}
						$pageWidgets[$widget_id]->widget_id = $widget_id;
						$pageWidgets[$widget_id]->widget_position = 'column' . $position;
						$pageWidgets[$widget_id]->ctx = $this->ctx;
						$pageWidgets[$widget_id]->acl_assistant = $this->acl_assistant;
						$pageWidgets[$widget_id]->moderator_mode = $this->moderator_mode;
					}
				}
			}
		}
		
		if ( !empty($widgets) ) {
			foreach ( $widgets as $key=>$val ) {
				$pageWidgets[$key] = $val;
			}
		}
		
		$this->widgets = $pageWidgets;
	}
	
	public function ajax_updateLayout ( $column, $layout ) {

		$this->ctx->db->begin();
		// тут поидее $layout это одномерный массив с widget_id, их последовательность и есть layout

		$column = substr($column, 6, 1);
		
		$node = $this->store->getObject(1);

		// пытаемся удалить элемент из других колонок
		foreach ($node->data['widgets_layout'] as $col=>$c_layout) {
			if ($column != $col) {
				$excess_elements = array_intersect($c_layout, $layout); // сначала поймем какие элементы у нас остались в колонках окромя той куда добавлен элемент
				foreach ($excess_elements as $key=>$value) unset($node->data['widgets_layout'][ $col ][ $key ]); // затем удалим их
			}
		}

		$node->data['widgets_layout'][ $column ] = $layout;
		
		// сохраняем
		$node->save();

		$this->ctx->db->end();
		$this->ctx->cp->set_data('0');
	}
	
	public function ajax_deleteWidget ( $widget_id ) {
		$this->ctx->db->begin();
		$node = $this->store->getObject(1);
		
		unset($node->data['widgets'][$widget_id]);

		foreach($node->data['widgets_layout'] as $column=>$layout) {
			$key = array_search($widget_id, $layout);
			if ($key!==false) {
				$columnLayout = array();
				foreach ($node->data['widgets_layout'][$column] as $old_key=>$id) {
					if ( $old_key != $key ) {
						$columnLayout[] = $id;
					}
				}
				$node->data['widgets_layout'][$column] = $columnLayout;
			}
		}

		// сохраняем
		$node->save();
		$this->ctx->db->end();

		$this->ctx->cp->set_data( $widget_id );
	}
	
	public function ajax_getSettingsHtml( $widget_id ) {
		$this->fillWidgetsList();
		
		$widget = $this->widgets[$widget_id];

		if (!isset($widget)) return false;

		$w_name = get_class($widget);
		
		$form_data = $widget->settingsForm();
		
		$w_settings = get_object_vars($widget);
		$w_settings['id'] = $widget_id;
		
		if (isset($form_data)) {
			require_once 'includes/form.php';
			$w_settings['form'] = init_form($form_data);
		}
		
		if ( isset($widget->widget_view) ) {
			$view_name = $widget->widget_view;
		} else {
			$view_name = 'WG_'.$w_name;
		}
		
		$wg_view = $this->rh->views->findByName($view_name.':settings');
		if ($wg_view) {
			$wg_view->data['settings'] = $w_settings;
			$this->ctx->cp->set_data( $wg_view->getContent() );
		}
	}
	
	public function ajax_updateSettings( $_params )	{
		php_parse_str($_params, $params);
		$this->ctx->db->begin();
		$node = $this->store->getObject(1);
		
		if ( isset($params['widget_id']) ) {
			$this->fillWidgetsList();
			$widget_id = $params['widget_id'];
			$widget = $this->widgets[ $widget_id ];
			
			$widget->beforeUpdateSettings($params);
			
			unset ($params['widget_id']);
			
			$node->data['widgets'][ $widget_id ]['params'] = $params;
			
			// сохраняем
			$node->save();
			$this->ctx->cp->set_data( $widget_id );
		} else {
			$this->ctx->cp->set_data( -1 );
		}
		$this->ctx->db->end();
	}
}
